// Utilities for local date handling with Asia/Shanghai timezone (UTC+8)

const TZ_OFFSET_MINUTES = 8 * 60

export function parseLocalDate(dateStr: string): Date {
  // Expect YYYY-MM-DD; create Date with UTC midnight
  // MySQL Date type stores date-only, Prisma reads it as UTC 00:00:00
  // So we need to pass a Date object whose UTC time is the target date
  return new Date(`${dateStr}T00:00:00.000Z`)
}

export function startOfDayLocal(date: Date): Date {
  const d = new Date(date)
  d.setUTCHours(0 - (TZ_OFFSET_MINUTES / 60), 0, 0, 0)
  return new Date(d.getTime() + TZ_OFFSET_MINUTES * 60 * 1000)
}

export function endOfDayLocal(date: Date): Date {
  const d = new Date(date)
  d.setUTCHours(23 - (TZ_OFFSET_MINUTES / 60), 59, 59, 999)
  return new Date(d.getTime() + TZ_OFFSET_MINUTES * 60 * 1000)
}

export function getWeekRangeMonday(dateStr: string): { start: Date; end: Date } {
  const d = parseLocalDate(dateStr)
  // JS: 0=Sun,1=Mon,... Move to Monday
  const day = (d.getDay() + 6) % 7 // Mon=0
  const start = new Date(d)
  start.setDate(start.getDate() - day)
  const end = new Date(start)
  end.setDate(start.getDate() + 6)
  return { start, end }
}

export function getDateRangeDay(dateStr: string): { start: Date; end: Date } {
  const d = parseLocalDate(dateStr)
  const start = d
  const end = new Date(d)
  end.setDate(end.getDate() + 1)
  end.setMilliseconds(end.getMilliseconds() - 1)
  return { start, end }
}


